package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQueryObject;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionRepository regionRepository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Region region) {
        region.setId(null);
        regionRepository.save(region);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }

    @Override
    public void update(Region region) {
        regionRepository.save(region);
    }

    @Override
    public Region get(String id) {
        return regionRepository.findById(id).orElse(null);
    }

    @Override
    public Page<Region> query(RegionQueryObject qo) {
        // 创建拼接对象
        Query query = new Query();
        // 使用PageRequest.of,传入当前页 - 1 (记得-1, 因为当前页从0开始), 页面显示条数, 排序规则, 排序的列
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template, qo, query, pageable, Region.class);
    }

    @Override
    public void changeHotValue(String id, int hot) {

        // 全量更新操作
        // 查询
        //Region region = this.get(id);
        //// 替换
        //region.setIshot(hot);
        //// 更新
        //this.update(region);

        // 创建拼接对象
        Query query = new Query();
        // 添加条件
        query.addCriteria(Criteria.where("_id").is(id));
        // 创建Update对象
        Update update = new Update();
        update.set("ishot", hot);
        template.updateFirst(query, update, Region.class);
    }



    @Override
    public List<Region> getHotRegion() {
        return regionRepository.findByIshotOrderBySequence(1);
    }

    @Override
    public List<Region> list() {
        return regionRepository.findAll();
    }
}
